package com.bawei.mall.search.controller;

import com.alibaba.fastjson2.JSONObject;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.utils.StringUtils;
import com.bawei.common.log.annotation.Log;
import com.bawei.es.domain.EsDocsQuery;
import com.bawei.mall.product.domain.reponse.ProductInfoResponse;
import com.bawei.mall.search.domain.request.EsSearchReq;
import com.bawei.mall.search.domain.request.SearchReq;
import com.bawei.mall.search.service.SearchService;
import com.bawei.mall.search.utils.SearchResultUtils;
import lombok.extern.log4j.Log4j2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author DongZl
 * @description: 搜索控制层
 * @Date 2022-10-24 下午 02:54
 */
@RestController
@RequestMapping("/search")
@Log4j2
public class SearchController {


    @Autowired
    private SearchService searchService;

    /**
     * 1、查询到数据
     * 2、指定模板
     * 3、渲染模板
     * 4、返回页面
     *
     * @param searchReq
     * @param model
     * @return
     */
    @GetMapping("product")
    public String search(SearchReq searchReq, Model model){
        log.info("搜索：[{}]", JSONObject.toJSONString(searchReq));
        if (StringUtils.isEmpty(searchReq.getKeyWord())){
            return "search";
        }

        searchService.search(searchReq);

        List<ProductInfoResponse> list = SearchResultUtils.getList();
        Long total = SearchResultUtils.getTotal();
        log.info(JSONObject.toJSONString(list));
        model.addAttribute("dataList", list);
        model.addAttribute("total", total);
        model.addAttribute("searchReq",searchReq);
        return "search";
    }

    @Log(title = "查询es商品信息")
    @PostMapping("searchEsProductInfo")
    public R<EsDocsQuery> searchEsProductInfo(@RequestBody EsSearchReq esSearchReq) {
        R<EsDocsQuery> esDocsQuery = searchService.searchEsProductInfo(esSearchReq);

        return esDocsQuery;
    }



}
